package soa.security.web.action;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import soa.security.Constants;
import soa.security.domain.Account;
import soa.security.domain.Organization;
import soa.security.web.LdapAuthenticationFilter;
import soa.security.web.support.action.LdapModelAction;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

public class AccountAction extends LdapModelAction<Account> {

	private static final long serialVersionUID = 6145782274740130027L;

	private File file; // 上传的文件
	private String fileFileName;

	private String passwordNew;
	private String personId;
	private String base;
	private String dns;
	private boolean globaled;

	public String grid() {
		if (StringUtils.isBlank(organizationId))
			return SUCCESS;
		updateResultContent(accountMgrService.allAccounts(organizationId,
				buildContext().getParameters(), subTree, this.page.getRequest()));
		return SUCCESS;
	}

	public String gridRoot() {
		updateResultContent(accountMgrService.findByBase(base));
		return SUCCESS;
	}

	public String edit() {
		Account account = getModel();

		if (StringUtils.isBlank(dnp)) {
			this.pageResult.addData("personId", personId);
		} else {
			// 为了防止前台校验
			account.setPassword(Constants.ACCOUNT_INIT_PWD);
			this.pageResult.addData("personId", account.getPersonBid());
		}

		Organization or = account.getOrganization();
		if (or == null)
			or = getOrganization(organizationId);
		account.setOrganization(or);

		orId = account.getOrganization().getBid();

		updateResultContent(account);
		return SUCCESS;
	}

	public String view() {
		Account account = getModel();
		Organization or = account.getOrganization();
		if (or == null)
			or = getOrganization(organizationId);
		account.setOrganization(or);

		orId = account.getOrganization().getBid();
		return SUCCESS;
	}

	public String doneSave() {
		accountMgrService.addAccount(organizationId, getModel());
		return SUCCESS;
	}

	public String doneUpdate() {
		accountMgrService.updateAccount(organizationId, getModel());
		return SUCCESS;
	}

	public String upload() {
		return SUCCESS;
	}

	public String doneUpload() throws Exception {
		InputStream is = null;
		try {
			is = new FileInputStream(getFile());

			String extension = FilenameUtils.getExtension(getFileFileName());
			String[] includeExts = { "xlsx", "xls" };

			if (!ArrayUtils.contains(includeExts, extension)) {
				throw new Exception("不支持的文件后缀，只能导入Excel文件");
			}
			//提交信息获取不到机构，从当前登录用户的session获取
			if (organizationId == null || "".equals(organizationId)) {
				HttpServletRequest request = ServletActionContext.getRequest();
				HttpSession session = request.getSession(false);
				Organization or = (Organization)(session.getAttribute(LdapAuthenticationFilter.SESSION_ORGANIZATION_KEY));
				if (or != null) {
					organizationId = or.getBid();
				}
			}
			boolean result = accountMgrService.importAccounts(organizationId,
					is);
			if (!result)
				throw new Exception("导入失败");
		} catch (Exception e) {
			log.error("导入失败", e);
			throw new Exception(e.getMessage());
		} finally {
			IOUtils.closeQuietly(is);
		}

		return SUCCESS;
	}

	public String pwdUpdate() {
		return SUCCESS;
	}

	public String doneValidateBid() throws Exception {
		Account a = getModel();
		Account exsit = accountMgrService.existAccount(organizationId, a);

		if (exsit != null && !dnp.equals(exsit.getDn().toString()))
			throw new Exception("该账号已经被使用");
		return SUCCESS;
	}

	public String doneValidatePwd() throws Exception {
		Account a = getModel();
		boolean flag = accountMgrService.compareCredentials(dnp,
				a.getPassword());

		if (!flag)
			throw new Exception("原始密码不正确");
		return SUCCESS;
	}

	public String donePwdUpdate() {
		Account account = getModel();

		accountMgrService.pwdUpdate(organizationId, account.getUid(),
				passwordNew);
		return SUCCESS;
	}

	public String donePwdReset() {
		String[] ids = StringUtils.split(dns, ";");
		if (ids != null) {
			for (String string : ids) {
				accountMgrService.pwdReset(string);
			}
		}
		return SUCCESS;
	}

	public String doneDisable() {
		accountMgrService.disable(dnp);
		return SUCCESS;
	}

	public String doneEnable() {
		accountMgrService.enable(dnp);
		return SUCCESS;
	}

	@Override
	public String remove() {
		accountMgrService.remove(dnp);
		return SUCCESS;
	}

	public String template() {
		HttpServletResponse response = ServletActionContext.getResponse();
		FileInputStream fis = null;
		try {
			File file = accountMgrService.getTemplate();
			String filename = new String(file.getName().getBytes(
					Constants.DEFAULT_CHARSET), Constants.DEFAULT_CHARSET);

			response.setCharacterEncoding(Constants.DEFAULT_CHARSET);
			response.setContentType("application/octet-stream");
			response.setHeader("Content-Disposition", "attachment; filename="
					+ filename);

			fis = new FileInputStream(file);
			IOUtils.copy(fis, response.getOutputStream());

			response.getOutputStream().flush();
			response.flushBuffer();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(fis);
		}

		return null;
	}

	public String errorLog() {
		HttpServletResponse response = ServletActionContext.getResponse();
		FileInputStream fis = null;
		try {
			File file = accountMgrService.getError();
			String filename = new String(file.getName().getBytes(
					Constants.DEFAULT_CHARSET), Constants.DEFAULT_CHARSET);

			response.setCharacterEncoding(Constants.DEFAULT_CHARSET);
			response.setContentType("application/octet-stream");
			response.setHeader("Content-Disposition", "attachment; filename="
					+ filename);

			fis = new FileInputStream(file);
			IOUtils.copy(fis, response.getOutputStream());

			response.getOutputStream().flush();
			response.flushBuffer();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(fis);
		}

		return null;
	}

	@Override
	protected Account findByDn(String dn) {
		return accountMgrService.findByDn(dn);
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	public String getPasswordNew() {
		return passwordNew;
	}

	public void setPasswordNew(String passwordNew) {
		this.passwordNew = passwordNew;
	}

	public String getPersonId() {
		return personId;
	}

	public void setPersonId(String personId) {
		this.personId = personId;
	}

	public String getBase() {
		return base;
	}

	public void setBase(String base) {
		this.base = base;
	}

	public String getDns() {
		return dns;
	}

	public void setDns(String dns) {
		this.dns = dns;
	}

	public boolean isGlobaled() {
		return globaled;
	}

	public void setGlobaled(boolean globaled) {
		this.globaled = globaled;
	}
}
